package com.cjc.sport;

import com.cjc.sport.entity.NumEnum;
import com.cjc.sport.entity.ReturnJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

/**
 * ========================
 * Created with intellij IDEA
 * 创建者：杜一平
 * 日期：2017/1/22（星期一）
 * 时间：08：00
 * 说明：拦截SQLExeption错误
 * ==========================
 */
@ControllerAdvice
public class MyControllerAdvice {

    /**
     * 日志配置
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MyControllerAdvice.class);

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder 默认参数
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     *
     * @param model 默认值
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

    /**
     * 数据库异常捕捉处理
     *
     * @param ex 异常信息
     * @return 封装标准参数
     */
    @ResponseBody
    @ExceptionHandler(value = SQLException.class)
    public ReturnJson errorHandler(Exception ex) {
        LOGGER.error("It's a SQLException error");
        return new ReturnJson(NumEnum.FAIL.getIndex(), ex.getMessage());
    }

}